﻿using MaterialDesignColors;
using MyToDo.Common;
using MyToDo.Common.Models;
using MyToDo.Extensions;
using MyToDo.Service.Memo;
using MyToDo.Service.ToDo;
using MyToDo.Views.Dialogs;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.ViewModels
{
    public class IndexViewModel:NavigationViewModel
    {
        private readonly IToDoService toDoService;
        private readonly IMemoService memoService;
        private readonly IDialogHostService dialog;
        private readonly IRegionManager regionManager;
        public DelegateCommand<ToDoDto> ToDoCompltedCommand { get; private set; }
        public DelegateCommand<MemoDto> EditMemoCommand { get; private set; }
        public DelegateCommand<ToDoDto> EditToDoCommand { get; private set; }
        public DelegateCommand<string> ExecuteCommand { get; private set; }
        public DelegateCommand<TaskBar> NavigateCommand { get; private set; }
        public IndexViewModel(IDialogHostService dialog,IContainerProvider provider):base(provider)
        {            
            TaskBars =new ObservableCollection<TaskBar>();
            //ToDoDtos = new ObservableCollection<ToDoDto>();
            //MemoDtos = new ObservableCollection<MemoDto>();
            CrateTaskBars();
            //CreateTestData();           
            ExecuteCommand = new DelegateCommand<string>(Execute);
            EditMemoCommand = new DelegateCommand<MemoDto>(AddMemo);
            EditToDoCommand = new DelegateCommand<ToDoDto>(AddToDo);
            ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Complted);
            this.toDoService = provider.Resolve<IToDoService>();
            this.memoService = provider.Resolve<IMemoService>();
            this.dialog = dialog;
            this.regionManager = provider.Resolve<IRegionManager>();
            NavigateCommand = new DelegateCommand<TaskBar>(Navigate);
        }

        private void Navigate(TaskBar obj)
        {
            if (string.IsNullOrWhiteSpace(obj.Target)) return;
            NavigationParameters param = new NavigationParameters();
            if (obj.Title == "已完成") {
                param.Add("Value", 2);
            }
            regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(obj.Target, param);
        }

        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            var summaryResult = await toDoService.SummaryAsync();
            if (summaryResult.Status) {
                Summary = summaryResult.Result;
                Refresh();
            }
            base.OnNavigatedTo(navigationContext);
        }
        private async void Complted(ToDoDto obj)
        {
            var updateResult = await toDoService.UpdateAsync(obj);
            if (updateResult.Status)
            {
                //var todo = ToDoDtos.FirstOrDefault(t => t.Id.Equals(obj.Id));
                var todo = Summary.ToDoList.FirstOrDefault(t => t.Id.Equals(obj.Id));
                if (todo != null)
                {
                    //ToDoDtos.Remove(todo);
                    Summary.ToDoList.Remove(todo);
                    Summary.CompletedCount -= 1;
                    Refresh();
                }
                aggregator.SendMessage("已完成");
            }
        }

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增待办":
                    AddToDo(null);
                    break;
                case "新增备忘录":
                    AddMemo(null);
                    break;
            }
        }
        async void AddToDo(ToDoDto model) {
            DialogParameters param = new DialogParameters();
            if (model != null)
                param.Add("Value", model);
            var dialogResult = await dialog.ShowDialog("AddToDoView", param);
            if (dialogResult.Result == ButtonResult.OK) {
                var todo = dialogResult.Parameters.GetValue<ToDoDto>("Value");
                if (todo.Id > 0) {
                    var updateResult = await toDoService.UpdateAsync(todo);
                    if (updateResult.Status)
                    {
                        //var todoModel =  ToDoDtos.FirstOrDefault(t=>t.Id.Equals(todo.Id));
                        var todoModel = Summary.ToDoList.FirstOrDefault(t => t.Id.Equals(todo.Id));
                        if (todoModel != null) {
                            todoModel.Title = todo.Title;
                            todoModel.Content = todo.Content;
                        }
                    }
                } else {
                    var addResult = await  toDoService.AddAsync(todo);
                    if (addResult.Status) {
                        //ToDoDtos.Add(addResult.Result);
                        Summary.ToDoList.Add(addResult.Result);
                        Summary.Sum += 1;
                        Refresh();
                    }
                }
            }
        }
        async void AddMemo(MemoDto model) {
            DialogParameters param = new DialogParameters();
            if (model != null)
                param.Add("Value", model);
           var dialogResult = await dialog.ShowDialog("AddMemoView", param);
            if (dialogResult.Result == ButtonResult.OK) {
                var memo = dialogResult.Parameters.GetValue<MemoDto>("Value");
                if (memo.Id > 0)
                {
                    var updateResult = await memoService.UpdateAsync(memo);
                    if (updateResult.Status)
                    {
                        //var memoModel = MemoDtos.FirstOrDefault(t => t.Id.Equals(memo.Id));
                        var memoModel = Summary.MemoList.FirstOrDefault(t => t.Id.Equals(memo.Id));
                        if (memoModel != null)
                        {
                            memoModel.Title = memo.Title;
                            memoModel.Content = memo.Content;
                        }
                    }
                }
                else
                {
                    var addResult = await memoService.AddAsync(memo);
                    if (addResult.Status)
                    {
                        //MemoDtos.Add(addResult.Result);
                        Summary.MemoList.Add(addResult.Result);
                    }
                }
            }
        }

       
        //private ObservableCollection<ToDoDto> toDoDtos;

        //public ObservableCollection<ToDoDto> ToDoDtos
        //{
        //    get { return toDoDtos; }
        //    set { toDoDtos = value; RaisePropertyChanged(); }
        //}
        //private ObservableCollection<MemoDto> memoDtos;

        //public ObservableCollection<MemoDto> MemoDtos
        //{
        //    get { return memoDtos; }
        //    set { memoDtos = value; RaisePropertyChanged(); }
        //}


        private SummaryDto summary;

        public SummaryDto Summary
        {
            get { return summary; }
            set { summary = value; RaisePropertyChanged(); }
        }

        void CreateTestData() {            
            for (int i = 0; i < 10; i++)
            {
                //ToDoDtos.Add(new ToDoDto() { Title = "待办" + i, Content = "正在处理中。。。" });
                //MemoDtos.Add(new MemoDto() { Title = "备忘" + i, Content = "我的密码" });
            }
        }
        private ObservableCollection<TaskBar> taskBars;        

        public ObservableCollection<TaskBar> TaskBars
        {
            get { return taskBars; }
            set { taskBars = value;RaisePropertyChanged(); }
        }
        void CrateTaskBars() 
        {
            TaskBars.Add(new TaskBar() { Icon = "ClockFast", Title = "汇总", Color = "#FF0CA0FF", Target = "ToDoView" });
            TaskBars.Add(new TaskBar() { Icon = "ClockCheckOutline", Title = "已完成",  Color = "#FF1ECA3A", Target = "ToDoView" });
            TaskBars.Add(new TaskBar() { Icon = "ChartLineVariant", Title = "完成比例",  Color = "#FF02C6DC", Target = "" });
            TaskBars.Add(new TaskBar() { Icon = "PlaylistStar", Title = "备忘录",  Color = "#FFFFA000", Target = "MemoView" });
        }
        void Refresh() {
            TaskBars[0].Content = Summary.Sum.ToString();
            TaskBars[1].Content = Summary.CompletedCount.ToString();
            TaskBars[2].Content = Summary.CompletedRatio.ToString();
            TaskBars[3].Content = Summary.MemoCount.ToString();
        }
    }
}
